import axios from 'axios';
import store from '../store/index';
import WebStorageCache from 'web-storage-cache';
import { Message, LoadingBar, Modal } from 'view-ui-plus';


let util = {};

const ajaxUrl = 'http://template.test/api';
// const ajaxUrl = 'https://amour.ap-1.sharedwithexpose.com//api';

util.ajax = axios.create({
  baseURL: ajaxUrl,
  timeout: 30000
});

util.api = ajaxUrl;
util.oauthUrl = ajaxUrl;

util.isIOS = () => {
  return navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
};


/**
 * 缓存类
 * @type {module:web-storage-cache.WebStorageCache}
 */
util.wsCache =  new WebStorageCache();

/**
 * 获取微信JSSDK的url
 * @returns {string}
 */
util.getJsSdkUrl = () => {
  // IOS
  if (util.isIOS()) {
    return window.sessionStorage.getItem('enter_url')
  } else {
    // Android
    return window.location.href.split('#')[0]
  }
}


/**
 * 重置分享链接
 * @param url
 * @param query
 * @param inviteId
 * @returns {string}
 */
util.getShareUrl = (url, query, inviteId) => {
  // 加绑定idc
  if (inviteId) {
    query.invite_id = inviteId;
  }
  // 重置
  let queryArray = [];
  // 循环拿取
  for (let i in query) {
    queryArray.push(i + '=' + query[i]);
  }
  return url + '?' + queryArray.join('&');
}

/**
 * 获取定位
 * @param refresh
 * @returns {Promise<unknown>}
 */
util.getLocation = (refresh = false) => {
  return new Promise((resolve, reject) => {

    let geo = util.wsCache.get('geo');
    if (geo && !refresh) {
      return resolve(geo);
    }

    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(
        function (position) {
          let params = {
            lng: position.coords.longitude,
            lat: position.coords.latitude
          };
          util.wsCache.set('geo', params, 30 * 60 * 1000)
          resolve(params);
        },
        function (e) {
          resolve(null);
        }
      )
    } else {
      resolve(null);
    }
  });

}

/**
 * 开始loading
 */
util.openLoading = () => {
  LoadingBar.start();
}

/**
 * 结束loading
 */
util.closeLoading = () => {
  // 延迟100毫秒关闭
  setTimeout(() => {
    // 关闭loading
    LoadingBar.finish();
  }, 200);
}

/**
 * 补充ajax接口warehouse
 * @param url
 * @param params
 * @returns {{}}
 */
util.addWarehouseToParams = (url = null, params = {}) => {
  if (url) {
    let path = url.substring(7);
    let currentPositionAddress = util.wsCache.get("chooseCurrentPositionAddress")
    let arr = ['category', 'goods', 'special/week', 'recommend', 'cart', 'banner', 'discount/category', 'discount', 'discount/goods'];
    let patten = /^goods\/\d{1,}$/;
    if (currentPositionAddress && (arr.find(item=>item === path) || patten.exec(path))) {
      params.warehouse_id = currentPositionAddress.warehouse_id;
    }

  }
  return params;
}


/**
 * alert方法
 * @param content
 * @param type
 * @param duration
 */
util.alert = (content, type = 'success', duration = 1500) => {
  Message[type]({
    content,
    duration
  });
}

/**
 * success toast 方法
 * @param content
 */
util.success = (content) => {
  Message.success({
    content,
    duration: 2
  });
}


/**
 * error toast 方法
 * @param content
 * @param duration
 */
util.error = (content, duration = 2) => {
  Message.error({
    content,
    duration
  });
}


/**
 * dialog alert 方法
 * @param content
 * @param title
 */
util.dialog = (content, title = '提示') => {
  Modal.info({
    content,
    title
  });
}


/**
 *
 * @param content
 * @param func
 * @param cat
 */
util.confirm = (content, func, cat = {}) => {
  Modal.confirm({
    content,
    title: '提示',
    onOk: func,
    onCancel: cat,
  });
}


// 修改时间
util.formatDateTime = (date)  =>{
  if (!(date instanceof Date)) {
    return date;
  }
  let y = date.getFullYear();
  let m = date.getMonth() + 1;
  m = m < 10 ? ('0' + m) : m;
  let d = date.getDate();
  d = d < 10 ? ('0' + d) : d;
  return y + '-' + m + '-' + d;
}




/**
 * 验证是否存在权限
 * @param code
 * @returns {boolean}
 */
util.filterPermission =  (code) => {
  let bool = false
  let user = store.state.user.data;
  if (!user || !user.role || !code) {
    return bool;
  }
  let index = user.permission_list.findIndex((item) => item == code);

  return index >= 0;
}

export default util;

